import { useUserStore } from '@/stores/user'
import type { Directive, DirectiveBinding } from 'vue';

// 使用了类型进行注册
const permission: Directive<HTMLElement, string> = {
	// mounted :Directive挂载生命周期
	mounted: (el: HTMLElement, bind: DirectiveBinding) => {
		const store = useUserStore();
		// roleData需要自己去引入
		const roleData = store.permissions || [];
		const {value} = bind;
		// 判断是否为超级管理员
		const isAdmin = store.user?.admin;
		if (isAdmin) return;
		// 判空以及判断类型
		if (value && value instanceof Array) {
			if (value.length > 0) {
				const permissionRoles = value;
				// 判断是否存在权限
				const hasPermission = roleData.some((role) => {
					return permissionRoles.includes(role);
				});
				// 返回值为false 删除节点
				if (!hasPermission && el && el.parentNode) {
					return el.parentNode && el.parentNode.removeChild(el);
				}
			}
		} else if (value !== undefined && value !== null) {
			throw new Error('权限值为空或权限值类型错误');
		}
	},
};

export default permission;

export const hasPermission = (checkPermissions: string[]) => {
	const {permissions, user} = useUserStore();
	if (user.admin) {
		return true;
	}
	return permissions.some((role) => {
		return checkPermissions.includes(role);
	});
};
